package com.medicalfee.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractFormController;

import com.medicalfee.dao.ReimbursementList;
import com.medicalfee.dao.ReimbursementListDAO;
import com.medicalfee.dao.StuffInfo;
import com.medicalfee.dao.StuffInfoDAO;
import com.medicalfee.util.CountReimbursementUtil;

public class InsertReimbursementController extends AbstractFormController {
	private StuffInfoDAO stuffInfoDao;
	private ReimbursementListDAO reimbursementListDao;

	InsertReimbursementController() {
		setCommandClass(ReimbursementList.class);
	}

	public void setStuffInfoDao(StuffInfoDAO stuffInfoDao) {
		this.stuffInfoDao = stuffInfoDao;
	}

	public void setReimbursementListDao(
			ReimbursementListDAO reimbursementListDao) {
		this.reimbursementListDao = reimbursementListDao;
	}

	@Override
	protected ModelAndView processFormSubmission(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException be)
			throws Exception {
		// TODO Auto-generated method stub
		ReimbursementList reimbursement = (ReimbursementList) command;
		StuffInfo stuffInfo = (StuffInfo) stuffInfoDao.getStuffByHql(
				"from StuffInfo where id="
						+ Integer.parseInt(request.getParameter("sid"))).get(0);
		reimbursement.setSid(stuffInfo);
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		reimbursement.setDate(format.parse(request.getParameter("date")));
		String startDate = request.getParameter("startDate");
		if (!startDate.equals("")) {
			reimbursement.setStartDate(format.parse(startDate));
		} else {
			reimbursement.setStartDate(null);
		}
		String endDate = request.getParameter("endDate");
		if (!startDate.equals("")) {
			reimbursement.setEndDate(format.parse(endDate));
		} else {
			reimbursement.setEndDate(null);
		}
		ReimbursementList newReimbursement = CountReimbursementUtil
				.countReimbursement(reimbursement);
		stuffInfoDao.insertOrUpdateStuff(newReimbursement.getSid());
		reimbursementListDao.InsertReimbursement(newReimbursement);
		JSONObject json = new JSONObject();
//		JSONObject reimbursementJson = JSONObject.fromObject(newReimbursement);
		json.put("success", true);
//		json.put("content", reimbursementJson);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(json.toString());
		return null;
	}

	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException be) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
